package com.bodacn.packapp;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.provider.Settings;
import android.text.InputType;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapFault;
import org.ksoap2.transport.HttpResponseException;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.os.Environment.MEDIA_MOUNTED;
import static android.view.KeyEvent.ACTION_UP;

public class GuideActivity extends AppCompatActivity implements View.OnClickListener {
    private final static String TAG = GuideActivity.class.getSimpleName();
    private final static int MSG_ChangePSWOver=9001;
    private final static int MSG_LoginCheckOver=9002;
    private final static int MSG_AllowScan=9003;
    private final static int MSG_CheckNetWork=9004;
    private Button btn_LoginSYS, btn_ExitSYS;
    private ImageButton btn_guide_setup;
    private EditText edit_LoginUserNo,edit_LoginPassword,edit_CardNo;
    private TextView txt_CPUID,txt_SoftVer;
    FrameLayout mFlContainer,mFlCardBack,mFlCardFront;
    LinearLayout linerCardBack,linerCardFront;
    private AnimatorSet mRightOutSet; // 右出动画
    private AnimatorSet mLeftInSet; // 左入动画
    public static boolean mIsShowBack,NeedUpdate=false;
    /* 保存解析的XML信息 */
    HashMap<String, String> ServerConfig;
    private Context mContext;
    //全局提示;
    Toast curToast;
    //全局变量
    String STORE_NAME = "Settings";
    //服务器地址
    String serviceUrl="http://192.168.10.12/tvservice";
    String apiUrl="";
    String termNo="00000";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String CPUID,curLoginUserNo,curLoginUser,curFactory, curDepartNo,curDepart,curLoginTime ,language="中文",curUserPower,curTime;//操作员所属部门等信息;
    int curOperateTime =600,spaceSec=15,switchCount=5;//工作分钟
    int curPlaceCount=60;//工位数;
    String SQLAddr="",SQLUser="",SQLPsw="",SQLDBName="";
    private JSONArray loginJSONArray;//用于接收登陆返回信息;
    private ProgressDialog waitDialog = null;
    boolean ScanSign=false;//执行过程中
    //初始化定时器;
    private Timer netTimer;
    private TimerTask  netTimeTask;
    //升级更新部分
    private PopupWindow popupWindow;
    private TextView txt_update;
    private ProgressBar progress_update;
    private Button btn_update;
    private TextView txt_SoftVer2;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    //升级相关的
    HashMap<String, String> mHashMap;
    //下载的ID
    private String apkname;
    private String apkpath;
    int contentLen=0;//文件大小；
    private static final int PROGRESS_MAX = 0X1;
    private static final int UPDATE = 0X2;
    FrameLayout mainLinerLayout;
    int newVer=0;
    //核心设置的代码
    protected void switchLanguage() {

        //读取配置文件-设置语言
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        serviceUrl=settings.getString("serviceUrl",serviceUrl);
        apiUrl=settings.getString("apiUrl",apiUrl);
        termNo=settings.getString("termNo",termNo);
        language=settings.getString("language",language);
        spaceSec =settings.getInt("spaceSec",spaceSec);
        switchCount=settings.getInt("switchCount",switchCount);
        SQLAddr=settings.getString("SQLAddr",SQLAddr);
        SQLUser=settings.getString("SQLUser",SQLUser);
        SQLPsw=settings.getString("SQLPsw",SQLPsw);
        SQLDBName=settings.getString("SQLDBName",SQLDBName);
        //数据连接类赋值;
        MainApplication.ServerIP=SQLAddr;
        MainApplication.UserName=SQLUser;
        MainApplication.Password=SQLPsw;
        MainApplication.DBName=SQLDBName;
        MainApplication.apiUrl=apiUrl;
        System.out.println("1--------------SQLAddr:"+SQLAddr+" SQLUser:"+SQLUser+" SQLPsw:"+SQLPsw+" SQLDBName:"+SQLDBName+" apiUrl:"+apiUrl);
        //获取资源
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {

            case "en":
                config.locale = new Locale("en","");
                resources.updateConfiguration(config, dm);
                break;
            case "km":
                config.locale = new Locale("km","");
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
        }
    }


    //启动定时器;
    private void checkNetTimer(){
        if (netTimer ==null) {
            netTimer = new Timer();
            System.out.println("onCreate timer---------------------------------2.1");
            //定时任务;
            if (netTimeTask == null) {
                netTimeTask = new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = MSG_CheckNetWork;
                        handler.sendMessage(message);
                    }
                };
            }
            System.out.println("onCreate timer---------------------------------2.2");
            netTimer.schedule(netTimeTask, 1000, 1000);
        }
    }
    //停止计时器;
    private void stopCheckNetTimer(){
        if (netTimer != null) {
            netTimer.cancel();
            netTimer = null;
        }
        if (netTimeTask != null) {
            netTimeTask.cancel();
            netTimeTask = null;
        }
        System.out.println("startTimer five---------------------------------Start");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //重设界面语言
        switchLanguage();
        //创建界面;
        setContentView(R.layout.activity_guide);
        initView();
        try {
            String SoftVer=getVersionName();
            txt_SoftVer.setText("VER:"+SoftVer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        hideIM(edit_LoginUserNo);
        //绑定动画;
        setAnimators(); // 设置动画
        setCameraDistance(); // 设置镜头距离
        mIsShowBack = true;//初始界面显正面刷卡,假设当前为反面;
        flipCard(mFlContainer);//先切换下动画
        mContext=this;

    }

    // 设置动画
    @SuppressLint("ResourceType")
    private void setAnimators() {
        mRightOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.anim.anim_out);
        mLeftInSet = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.anim.anim_in);
        // 设置点击事件
        mRightOutSet.addListener(new AnimatorListenerAdapter() {
            @Override public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                mFlContainer.setClickable(false);
                //显示背面的控件
                setBackCardCompontView(mIsShowBack,true);

            }
        });
        mLeftInSet.addListener(new AnimatorListenerAdapter() {
            @Override public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mFlContainer.setClickable(true);
                //根据要求显示背面的控件
                setBackCardCompontView(mIsShowBack,false);
            }
        });
    }

    // 改变视角距离, 贴近屏幕
    private void setCameraDistance() {
        int distance = 16000;
        float scale = getResources().getDisplayMetrics().density * distance;
        mFlCardFront.setCameraDistance(scale);
        mFlCardBack.setCameraDistance(scale);
    }

    // 翻转卡片
    public void flipCard(View view) {
        hideIM(view);
        // 正面朝上
        if (!mIsShowBack) {
            mRightOutSet.setTarget(mFlCardFront);
            mLeftInSet.setTarget(mFlCardBack);
            mRightOutSet.start();
            mLeftInSet.start();
            mIsShowBack = true;
        } else { // 背面朝上
            mRightOutSet.setTarget(mFlCardBack);
            mLeftInSet.setTarget(mFlCardFront);
            mRightOutSet.start();
            mLeftInSet.start();
            mIsShowBack = false;
        }

    }

    //设置是否显示背面的控件，不然会误按;
    public void setBackCardCompontView(boolean isVisible,boolean isAllShow){
        edit_LoginUserNo.setText("");
        edit_LoginPassword.setText("");
        edit_CardNo.setText("");
        if (isAllShow==true)
        {
            linerCardBack.setVisibility(View.VISIBLE);
            linerCardFront.setVisibility(View.VISIBLE);
        } else {
            if (isVisible == false) {
                linerCardBack.setVisibility(View.INVISIBLE);
                linerCardBack.setVisibility(View.INVISIBLE);
                linerCardFront.setVisibility(View.VISIBLE);
                edit_CardNo.setFocusable(true);
                edit_CardNo.setFocusableInTouchMode(true);
                edit_CardNo.setVisibility(View.VISIBLE);
                edit_CardNo.requestFocus();
                edit_CardNo.requestFocusFromTouch();
            } else {
                linerCardBack.setVisibility(View.VISIBLE);
                linerCardFront.setVisibility(View.INVISIBLE);
                edit_CardNo.setFocusable(false);
                edit_CardNo.setFocusableInTouchMode(false);
                edit_CardNo.setVisibility(View.INVISIBLE);
                edit_CardNo.setInputType(InputType.TYPE_NULL);
            }
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        //mIsShowBack = true;//初始界面显正面刷卡,假设当前为反面;
        //flipCard(mFlContainer);//先切换下动画
        System.out.println("onRestart-mIsShowBack:"+mIsShowBack);
        setBackCardCompontView(mIsShowBack,false);

    }

    private void initView()
    {

        mainLinerLayout=findViewById(R.id.mainLinerLayout);
        txt_CPUID=findViewById(R.id.txt_CPUID);
        txt_SoftVer=findViewById(R.id.txt_SoftVer);
        //按键;
        btn_LoginSYS=findViewById(R.id.btn_LoginSYS);
        btn_LoginSYS.setOnClickListener(this);
        btn_LoginSYS.setFocusableInTouchMode(false);
        btn_LoginSYS.setFocusable(false);
        btn_ExitSYS =findViewById(R.id.btn_ExitSYS);
        btn_ExitSYS.setOnClickListener(this);
        btn_ExitSYS.setFocusableInTouchMode(false);
        btn_ExitSYS.setFocusable(false);
        btn_guide_setup=findViewById(R.id.btn_guide_setup);
        btn_guide_setup.setOnClickListener(this);
        btn_guide_setup.setFocusableInTouchMode(false);
        btn_guide_setup.setFocusable(false);
        //显示控制;
        edit_CardNo=findViewById(R.id.edit_CardNo);
        edit_CardNo.setFocusable(false);
        edit_CardNo.setInputType(InputType.TYPE_NULL);
        edit_CardNo.setFocusableInTouchMode(false);
        edit_CardNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode== KeyEvent.KEYCODE_ENTER)&&(event.getAction()== ACTION_UP))
                {
                    curToast.cancel();
                    edit_CardNo.setEnabled(false);
                    playRingtone();
                    loginCheck();
                }
                return false;
            }
        });

        edit_LoginUserNo=(EditText)findViewById(R.id.edit_LoginUserNo);
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        edit_LoginUserNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if (event.getKeyCode()== KeyEvent.KEYCODE_ENTER)
                    {
                        edit_LoginPassword.setFocusable(true);
                    }
                }
                if ((keyCode== KeyEvent.KEYCODE_ENTER)&&(edit_CardNo.getText().toString().length()>0))
                {
                    edit_LoginPassword.setFocusable(true);
                    edit_LoginPassword.requestFocus();
                    edit_LoginPassword.requestFocusFromTouch();
                }
                return false;
            }
        });
        edit_LoginUserNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_LoginUserNo.setFocusable(true);
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginPassword,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_LoginUserNo.setFocusableInTouchMode(true);
        edit_LoginUserNo.setFocusable(true);
        edit_LoginUserNo.requestFocus();
        edit_LoginUserNo.requestFocusFromTouch();
        //显示控制;
        edit_LoginPassword=(EditText)findViewById(R.id.edit_LoginPassword);
        edit_LoginPassword.setInputType(InputType.TYPE_NULL);
        edit_LoginPassword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        edit_LoginPassword.setInputType(InputType.TYPE_NULL);
                        //1.得到InputMethodManager对象
                        InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                        //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                        IBinder windowToken = edit_LoginPassword.getWindowToken();
                        if (windowToken != null) {
                            imm.hideSoftInputFromWindow(windowToken, 0);
                        }
                        loginCheck();
                    }
                }
                return false;
            }
        });
        edit_LoginPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_LoginPassword.setFocusable(true);
                edit_LoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginPassword,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_LoginPassword.setFocusableInTouchMode(true);
        edit_LoginPassword.setFocusable(true);
        edit_LoginPassword.requestFocus();
        edit_LoginPassword.requestFocusFromTouch();
        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        //获取机器ID
        CPUID=getLocalCPUID().toUpperCase();
        txt_CPUID.setText(CPUID);
        //登陆卡片;
        mFlContainer=findViewById(R.id.loginframelayout);
        mFlCardBack=findViewById(R.id.main_fl_card_back);
        mFlCardFront=findViewById(R.id.main_fl_card_front);
        linerCardBack=findViewById(R.id.linerCardBack);
        linerCardFront=findViewById(R.id.linerCardFront);
        //提示框pd=new ProgressDialog(this);
        waitDialog= new ProgressDialog(this);
        waitDialog.setTitle(getString(R.string.SystemHint));
    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    private void showTips() {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.SystemExitConfirm))
                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent exit = new Intent(Intent.ACTION_MAIN);
                        exit.addCategory(Intent.CATEGORY_HOME);
                        exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(exit);
                        System.exit(0);
                        //finish();
                    }

                }).setNegativeButton(getString(R.string.Cancel),

                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框
    }
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign=false;
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("LoginCheck")==true)
                        {
                            loginJSONArray=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_LoginCheckOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("ChangePSW")==true)
                        {
                            loginJSONArray=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ChangePSWOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            Log.d("msg","ChangePSW--------------------1");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign=false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }



    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_CheckNetWork:
                    System.out.println("EnterMSG_CheckNetWork");
                    boolean networkState=false;
                    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP){
                        networkState=checkNetState_21();
                    }else{
                        networkState=checkNetState_21orNew();
                    }
                    try {
                        if (networkState==true){
                            stopCheckNetTimer();
                           Log.e(TAG,"serviceUrl"+serviceUrl);
                            GetServerConfig(serviceUrl+"/SysConfig.xml");
                            CheckWebUpdate(serviceUrl+"/UPDATE/packapp.xml");
                        } else{
                            Log.e(TAG,"-----------------------------------------CheckNetWork Err-----------------------------------------");
                        }
                    } catch (Exception e){


                    }
                    break;
                case MSG_ChangePSWOver:
                    Log.d("msg","ChangePSW--------------------1");
                    try {
                        if (loginJSONArray!=null) {
                            if (loginJSONArray.optJSONObject(0).get("ChangePSW").equals("OK")) {
                                curTime = "";
                                if (loginJSONArray.optJSONObject(0).has("Factory"))
                                    curFactory = loginJSONArray.optJSONObject(0).get("Factory").toString();
                                if (loginJSONArray.optJSONObject(0).has("DepartNo"))
                                    curDepartNo = loginJSONArray.optJSONObject(0).get("DepartNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("Depart"))
                                    curDepart = loginJSONArray.optJSONObject(0).get("Depart").toString();
                                if (loginJSONArray.optJSONObject(0).has("PlaceCount"))
                                    curPlaceCount = loginJSONArray.optJSONObject(0).getInt("PlaceCount");
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("OperateTime"))
                                    curOperateTime = loginJSONArray.optJSONObject(0).getInt("OperateTime");
                                if (loginJSONArray.optJSONObject(0).has("UserPower"))
                                    curUserPower = loginJSONArray.optJSONObject(0).getString("UserPower");
                                //设置系统时间
                                curToast.setText(getString(R.string.ChangPswOKInfo));
                                curToast.show();
                            } else {
                                curToast.setText(getString(R.string.ChangPswErrInfo));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_LoginCheckOver:
                case MSG_AllowScan:
                    edit_CardNo.setEnabled(true);
                    edit_CardNo.setFocusable(true);
                    edit_CardNo.selectAll();
                    try {
                        if (loginJSONArray!=null) {
                            if (loginJSONArray.optJSONObject(0).getString("LoginCheck").equals("OK")) {
                                String curLoginType = "A";//默认为组长登陆;
                                if (loginJSONArray.optJSONObject(0).has("Factory"))
                                    curFactory = loginJSONArray.optJSONObject(0).get("Factory").toString();
                                if (loginJSONArray.optJSONObject(0).has("DepartNo"))
                                    curDepartNo = loginJSONArray.optJSONObject(0).get("DepartNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("Depart"))
                                    curDepart = loginJSONArray.optJSONObject(0).get("Depart").toString();
                                if (loginJSONArray.optJSONObject(0).has("PlaceCount"))
                                    curPlaceCount = loginJSONArray.optJSONObject(0).getInt("PlaceCount");
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginTime"))
                                    curLoginTime = loginJSONArray.optJSONObject(0).get("LoginTime").toString();
                                if (loginJSONArray.optJSONObject(0).has("OperateTime"))
                                    curOperateTime = loginJSONArray.optJSONObject(0).getInt("OperateTime");
                                if (loginJSONArray.optJSONObject(0).has("LoginType"))
                                    curLoginType = loginJSONArray.optJSONObject(0).getString("LoginType");
                                if (loginJSONArray.optJSONObject(0).has("UserPower"))
                                    curUserPower = loginJSONArray.optJSONObject(0).getString("UserPower");
                                if (loginJSONArray.optJSONObject(0).has("CurTime"))
                                    curTime = loginJSONArray.optJSONObject(0).getString("CurTime");
                                //登陆界面;
                                loginOK(curLoginType);
                            } else {
                                curToast.setText(getString(R.string.PleaseCheckEmpNoPSW));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    //API版本23以下时调用此方法进行检测
    //因为API23后getNetworkInfo(int networkType)方法被弃用
    public boolean checkNetState_21(){
        try {
            //步骤1：通过Context.getSystemService(Context.CONNECTIVITY_SERVICE)获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            //步骤2：获取ConnectivityManager对象对应的NetworkInfo对象
            //NetworkInfo对象包含网络连接的所有信息
            //步骤3：根据需要取出网络连接信息
            //获取WIFI连接的信息
            NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            Boolean isWifiConn = networkInfo.isConnected();
            //获取移动数据连接的信息
            networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            Boolean isMobileConn = networkInfo.isConnected();
            System.out.println("Wifi是否连接:" + isWifiConn + " 移动数据是否连接:" + isMobileConn);
            return isWifiConn || isMobileConn;
        } catch (Exception e){
            Toast.makeText(this,"checkNetState_21"+e.getMessage(),Toast.LENGTH_LONG).show();
            return true;
        }
    }


    //API版本23及以上时调用此方法进行网络的检测
    //步骤非常类似
    public boolean checkNetState_21orNew(){
        //获得ConnectivityManager对象
        boolean isConnect=false;
        try {
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取所有网络连接的信息
            Network[] networks = new Network[0];
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                networks = connMgr.getAllNetworks();
            }
            //用于存放网络连接信息
            StringBuilder sb = new StringBuilder();
            //通过循环将网络信息逐个取出来
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    networkInfo = connMgr.getNetworkInfo(networks[i]);
                }
                if (isConnect == false) isConnect = networkInfo.isConnected();

            }
            return isConnect;
        } catch (Exception e){
            Toast.makeText(this,"checkNetState_21orNew",Toast.LENGTH_LONG).show();
            return false;
        }
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //当处理初始Fragment，则返回;
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            showTips();
        }
        return super.onKeyDown(keyCode, event);
    }

    //登陆校验;
    private void loginCheck(){
        int versionCode = getVersionCode(mContext);
        if (versionCode<newVer)
        {
            curToast.setText("当前版本非最新版,请升级后使用!");
            curToast.show();
            return;
        }
        //保存配置文件;
        saveSetup();
        if (NeedUpdate==true) {
            onStart();
            edit_LoginUserNo.setText("");
            edit_LoginPassword.setText("");
            edit_CardNo.setText("");

        } else {
            String tmpPassword = edit_LoginPassword.getText().toString();
            //登陆判断
            if (tmpPassword.length() > 0) {
                // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
                tmpPassword = new String(Base64.encode(tmpPassword.getBytes(), Base64.DEFAULT));
                Log.i("Test", "tmpPassword>>>" + tmpPassword);
            }
            edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
            edit_LoginPassword.setInputType(InputType.TYPE_NULL);
            String SqlComm = "Exec ScenePAD_LoginCheck @UserNo='" + edit_LoginUserNo.getText().toString() + "',@CardNo='" + edit_CardNo.getText().toString()
                    + "',@PassWord='" + tmpPassword.replaceAll("\r|\n", "") + "',@TermNo='" + termNo+ "',@CPUID='" + CPUID + "'";
            if (ScanSign==false) ReadSQLData(SqlComm);
            edit_LoginUserNo.setText("");
            edit_LoginPassword.setText("");
            edit_CardNo.setText("");
        }
    }
    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_update:
                //下载最新程序
                progress_update.setVisibility(View.VISIBLE);
                txt_update.setVisibility(View.VISIBLE);
                btn_update.setVisibility(View.GONE);
                String appUrl=mHashMap.get("url");
                String  appName=mHashMap.get("name");
                Log.e(TAG,"appUrl:"+appUrl+" appName:"+appName);
                //downloadAPK(appUrl, appName);
                downApkFromHttp(appUrl,appName);
                break;
            case R.id.btn_LoginSYS:
                if (edit_LoginUserNo.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputEmpNo));
                    curToast.show();
                } else loginCheck();
                break;
            case R.id.btn_ExitSYS:
                showTips();
                break;
            case R.id.btn_guide_setup:
                showSetup();
                break;
            case R.id.btn_EditUser:
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginUserNo,InputMethodManager.SHOW_FORCED);
                //changepsw();
                break;
                /*
            case R.id.btn_EditPass:
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm1 = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm1.showSoftInput(edit_LoginPassword,InputMethodManager.SHOW_FORCED);
                //changepsw();
                break;
                */
            default:
                break;
        }

    }

    //登陆成功
    private void loginOK(String LoginType){
        //隐藏键盘
        hideIM(edit_LoginPassword);
        new Thread(){
            public void run(){
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        //跳转前关闭键盘
        Intent mainActivity  = new Intent(GuideActivity.this, MainActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("LoginUserNo", curLoginUserNo);
        paramBundle.putString("LoginUser", curLoginUser);
        paramBundle.putString("LoginTime", curLoginTime);
        paramBundle.putString("CurFactory", curFactory);
        paramBundle.putString("CurDepartNo", curDepartNo);
        paramBundle.putString("CurDepart",curDepart);
        paramBundle.putInt("PlaceCount",curPlaceCount);
        paramBundle.putInt("OperateTime", curOperateTime);
        paramBundle.putString("serviceUrl", serviceUrl);
        paramBundle.putString("serviceUrlExt", serviceUrlExt);
        paramBundle.putString("CPUID",CPUID);
        paramBundle.putString("termNo",termNo);
        paramBundle.putInt("SpaceSec",spaceSec);
        paramBundle.putInt("SwitchCount",switchCount);
        paramBundle.putString("UserPower",curUserPower);
        mainActivity.putExtras(paramBundle);
        waitDialog.cancel();

        //启动主界面;
        startActivity(mainActivity);


    }

    private void saveSetup(){
        //登陆成功后保存配置;
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor set_editor=settings.edit();
        set_editor.putString("LoginUserNo",edit_LoginUserNo.getText().toString());
        set_editor.putString("serviceUrl",serviceUrl);
        set_editor.putString("termNo",termNo);
        set_editor.putString("language",language);
        set_editor.putString("SQLAddr", SQLAddr);
        set_editor.putString("SQLUser", SQLUser);
        set_editor.putString("SQLPsw", SQLPsw);
        set_editor.putString("SQLDBName", SQLDBName);
        set_editor.putInt("spaceSec",spaceSec);
        set_editor.putInt("switchCount",switchCount);
        set_editor.commit();
    }
    private void showSetup(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View guide_setup=inflater.inflate(R.layout.guide_setup, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的

        final EditText text_serverUrl=guide_setup.findViewById(R.id.text_serverUrl);
        text_serverUrl.setText(serviceUrl);
        final EditText text_termNo=guide_setup.findViewById(R.id.text_termNo);
        text_termNo.setText(termNo);
        final EditText text_spaceSec=guide_setup.findViewById(R.id.text_spaceSec);
        text_spaceSec.setText(String.valueOf(spaceSec));
        final EditText text_switchCount=guide_setup.findViewById(R.id.text_switchCount);
        text_switchCount.setText(String.valueOf(switchCount));
        final RadioGroup languageRG=(RadioGroup)guide_setup.findViewById(R.id.languageRG);
        if (language.equals("zh")==true) languageRG.check(R.id.RB1);
        if (language.equals("en")==true) languageRG.check(R.id.RB2);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.v("tag",text_serverUrl.getText().toString());
                        serviceUrl = text_serverUrl.getText().toString();
                        termNo = text_termNo.getText().toString();
                        if (text_spaceSec.getText().length()>0) spaceSec = Integer.valueOf(text_spaceSec.getText().toString());
                        if (text_switchCount.getText().length()>0) switchCount = Integer.valueOf(text_switchCount.getText().toString());
                        if (languageRG.getCheckedRadioButtonId() == R.id.RB1) language = "zh";
                        if (languageRG.getCheckedRadioButtonId() == R.id.RB2) language = "en";
                        System.out.println("语言:" + "---------------------" + language);
                        saveSetup();
                        hideIM(guide_setup);
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(guide_setup);
                Log.v("tag",getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SoftTitle));
        builder.show();
    }

    //修改密码
    private void changepsw(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View guide_setup=inflater.inflate(R.layout.guide_changepsw, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_password_old=(EditText)guide_setup.findViewById(R.id.text_password_old);
        final EditText text_password_new=(EditText)guide_setup.findViewById(R.id.text_password_new);
        final EditText text_password_new2=(EditText)guide_setup.findViewById(R.id.text_password_new2);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        hideIM(guide_setup);
                        String tmpOldPassword = text_password_old.getText().toString();
                        String tmpNewPassword = text_password_new.getText().toString();
                        String tmpNewPassword2 = text_password_new2.getText().toString();
                        Log.i("Test", "tmpOldPassword>>>" + tmpOldPassword+"----tmpNewPassword>>>" + tmpNewPassword+"----tmpNewPassword2>>>" + tmpNewPassword2);
                        if ((tmpNewPassword.length()>0) && (tmpNewPassword.equals(tmpNewPassword2))) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
                            tmpNewPassword = Base64.encodeToString(tmpNewPassword.getBytes(), Base64.DEFAULT);
                            if (tmpOldPassword.length()>0) tmpOldPassword=Base64.encodeToString(tmpOldPassword.getBytes(), Base64.DEFAULT);
                            Log.i("Test", "tmpOldPassword>>>" + tmpOldPassword+"----tmpNewPassword>>>" + tmpNewPassword);
                            //调用登陆过程;
                            String SqlComm="Exec ScenePAD_ChangePSW @UserNo='" + edit_LoginUserNo.getText().toString() + "',@OldPassWord='"+tmpOldPassword.replaceAll("\r|\n", "")+"',@NewPassWord='"+tmpNewPassword.replaceAll("\r|\n", "")+"'";
                            //调用WebService过程并处理界面更新;
                            ReadSQLData(SqlComm);
                        } else
                        {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                    field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText(getString(R.string.PasswordConfirmErr));
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    hideIM(guide_setup);
                    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialog,true); // true - 使之可以关闭(此为机关所在，其它语句相同)
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                Log.v("tag",getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SoftTitle));
        builder.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        checkNetTimer();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    //从网络获取版本升级文件
    public void GetServerConfig(String serviceUrl) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                Log.d("GetServerConfig","文件接收A:---"+serviceUrl);
                try {
                    ParseXmlService service = new ParseXmlService();
                    InputStream inStream = new URL(serviceUrl).openStream();
                    System.out.println("服务器配置文件获取成功....");
                    ServerConfig = service.parseXml(inStream);
                    System.out.println(ServerConfig);
                    System.out.println("服务器配置文件解析成功....");
                    return "OK";
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (Exception e){
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) Log.d(TAG,"获取服务器配置文件异常,错误异常抛出！");
                return "NO";
            }

            @Override
            protected void onPostExecute(String rtnstr) {
                super.onPostExecute(rtnstr);
                if ((rtnstr==null)||(rtnstr=="NO"))
                {
                    Toast.makeText(getApplicationContext(), "版本更新文件下载错误", Toast.LENGTH_LONG).show();
                    return;
                } else Log.d(TAG,"文件获取成功..");
                //判断版本是否相同;
                if (null != ServerConfig)
                {
                    SQLAddr = ServerConfig.get("ServerIP");
                    SQLUser =ServerConfig.get("UserName");
                    SQLPsw= ServerConfig.get("Password");
                    SQLDBName = ServerConfig.get("DBName");
                    apiUrl = ServerConfig.get("apiUrl");
                    MainApplication.ServerIP=SQLAddr;
                    MainApplication.UserName=SQLUser;
                    MainApplication.Password=SQLPsw;
                    MainApplication.DBName=SQLDBName;
                    MainApplication.apiUrl=apiUrl;
                    Log.i(TAG,"2--------------SQLAddr:"+SQLAddr+" SQLUser:"+SQLUser+" SQLPsw:"+SQLPsw+" SQLDBName:"+SQLDBName+" apiUrl:"+apiUrl);
                    setPref();
                }

            }
        }.execute(params);

    }


    //获取配置;
    private  void setPref() {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putString("SQLAddr", SQLAddr);
        editor.putString("SQLUser", SQLUser);
        editor.putString("SQLPsw", SQLPsw);
        editor.putString("SQLDBName", SQLDBName);
        editor.putString("apiUrl", apiUrl);
        editor.apply();
    }

    //获取软件版本;
    private String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }


    //获取CPU值
    public static String getLocalCPUID() {
        String str = "unKnow";
        String resultSerial = str;
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/devices/platform/cpu/uuid");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    resultSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return resultSerial;
    }


    //从网络获取版本升级文件
    public void CheckWebUpdate(String serviceUrl) {
        //组织参数传到匿名类中;
        Map<String, Object> params=new HashMap<String, Object>();
        params.put("serviceUrl",serviceUrl);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String, Object>, Void, String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                Log.d("GetWebUpdateFile","文件接收A:---"+serviceUrl);

                ParseXmlService service = new ParseXmlService();
                InputStream inStream = null;
                try {
                    inStream = new URL(serviceUrl).openStream();
                    mHashMap = service.parseXml(inStream);
                    Log.e(TAG,"版本文件获取成功....");
                    return "OK";
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (Exception e){
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) Log.d("TAG","获取服务器配置文件异常,错误异常抛出！");
                return "NO";

            }

            @Override
            protected void onPostExecute(String rtnstr) {
                super.onPostExecute(rtnstr);
                if ((rtnstr==null)||(rtnstr=="NO"))
                {
                    Toast.makeText(getApplicationContext(),"版本更新文件下载错误", Toast.LENGTH_LONG).show();
                    return;
                }
                //这部分主要用于UI更新;
                Log.d("msg","文件获取成功..");
                //判断版本是否相同;
                if (null != mHashMap)
                {
                    try {
                        int serviceCode = Integer.valueOf(mHashMap.get("version"));
                        newVer=serviceCode;
                        String hintInfo=mHashMap.get("hint");
                        if (hintInfo==null) hintInfo="1.更新已知Bug;";
                        Log.e(TAG,"hintInfo:"+hintInfo);
                        Log.e(TAG,"最新版本为" + serviceCode + "--------------------------------------------------");
                        // 版本判断
                        // 获取当前软件版本
                        int versionCode = getVersionCode(getApplication());
                        Log.e(TAG,"当前版本为" + versionCode + "--------------------------------------------------");
                        if (serviceCode > versionCode) {
                            Log.e(TAG,"准备显示升级提示对话框--------------------------------------------------");
                            // 显示提示对话框
                            showUpdate(hintInfo);
                        } else {
                            Toast.makeText(getApplicationContext(), "版本已是最新版", Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e){
                        Log.e(TAG,e.getMessage());
                    }
                }

            }
        }.execute(params);

    }



    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context)
    {
        int versionCode = 0;

        // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        try {
            versionCode = context.getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        }

        return versionCode;
    }


    public static String getFilePath(Context context) {
        String directoryPath="";
        if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ) {//判断外部存储是否可用
            directoryPath =context.getExternalFilesDir("").getAbsolutePath();
        }else{//没外部存储就使用内部存储
            directoryPath=context.getFilesDir().getAbsolutePath();
        }
        File file = new File(directoryPath);
        if(!file.exists()){//判断文件目录是否存在
            file.mkdirs();
        }
        return directoryPath;
    }

    private void downApkFromHttp(String fileUrl,String fileName){
        apkname=fileName;
        //设置下载的路径
        String filePath=getFilePath(this);
        //String filePath=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        //delete(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/"+apkname);
        //apkpath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/"+apkname;
        delete(filePath+File.separator+apkname);
        apkpath = filePath+File.separator+apkname;
        new DownLoad().execute(fileUrl,fileName);
    }

    public class DownLoad extends AsyncTask<String,Integer,String> {
        //在执行实际的后台操作前被UI Thread调用
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //准备下载前的初始进度
            progress_update.setProgress(0);
        }
        //在onPreExecute执行，该方法运行在后台线程中
        @Override
        protected String doInBackground(String... params) {
            try {
                int prSize=0,curLen=0;
                URL url = new URL(params[0]);
                String fileName= params[1];
                //获取连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //获取下载文件的大小
                contentLen = connection.getContentLength();
                //根据下载文件大小设置进度条最大值（使用标记区别实时进度更新）
                publishProgress(PROGRESS_MAX,contentLen);
                //循环下载（边读取边存入）
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new
                        File(apkpath)));
                int len =-1;
                byte[] bytes = new byte[1024];
                while((len=bis.read(bytes))!=-1){
                    bos.write(bytes,0,len);
                    bos.flush();
                    curLen+=len;
                    if (curLen>(prSize+256)) {
                        prSize=curLen;
                        //实时更新下载进度（使用标记区别最大值）
                        publishProgress(UPDATE, len);
                        //演示下载的图片太小，网速太快，休眠300毫秒，方便大家观察
                        //Thread.sleep(1);
                    }

                }
                bos.close();
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
            return "OK";
        }
        //在publishProgress被调用后，UI thread会调用这个方法
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            switch (values[0]){
                case PROGRESS_MAX:
                    progress_update.setMax(values[1]);
                    break;
                case UPDATE:
                    progress_update.incrementProgressBy(values[1]);
                    //获取下载进度百分比并更新textview
                    int i=(progress_update.getProgress()*100)/contentLen;
                    txt_update.setText("下载进度为："+i+"%");
                    break;
            }
        }
        //doInBackground方法执行完后被UI thread执行
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("OK")) {
                progress_update.setVisibility(View.GONE);
                txt_update.setText("下载成功准备安装");
                installAPK();
            } else {
                txt_update.setText("下载失败");
                //下载最新程序
                progress_update.setVisibility(View.GONE);
                txt_update.setVisibility(View.GONE);
                btn_update.setVisibility(View.VISIBLE);
                btn_update.setText("下载失败,请重试");
                curToast.setText(s);
                curToast.show();
            }
        }
    }


    //显示升级任务
    private void showUpdate(String hintInfo) {
        int deviationX=410,deviationY=430;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        //创建并初始化完成
        //创建并初始化完成
        if (popupWindow ==null) {
            popupWindow = new PopupWindow(this);
            popupWindow.setWidth(dm.widthPixels);
            popupWindow.setHeight(dm.heightPixels);
        }
        //取视图
        View popView= LayoutInflater.from(this).inflate(R.layout.softupdate, null);
        TextView txt_hintInfo=popView.findViewById(R.id.txt_hintInfo);
        TextView txt_BuildVer=popView.findViewById(R.id.txt_BuildVer);
        txt_BuildVer.setText("Build Ver:"+ Build.VERSION.CODENAME);
        TextView txt_FilePath=popView.findViewById(R.id.txt_FilePath);
        apkpath = getFilePath(this)+File.separator+apkname;
        txt_FilePath.setText(apkpath);

        String[] strings=hintInfo.split(";");
        StringBuilder builder=new StringBuilder();
        for (int i=0;i<strings.length;i++){
            if (builder.length()>0) builder.append("\r\n");
            builder.append(strings[i]);
        }
        txt_hintInfo.setText(builder.toString());
        btn_update=popView.findViewById(R.id.btn_update);
        btn_update.setOnClickListener(this);
        btn_update.requestFocus();
        txt_update=popView.findViewById(R.id.txt_update);
        txt_update.setVisibility(View.GONE);
        progress_update=popView.findViewById(R.id.progress_update);
        progress_update.setProgress(0);
        progress_update.setVisibility(View.GONE);
        txt_SoftVer2=popView.findViewById(R.id.txt_SoftVer2);
        try {
            txt_SoftVer2.setText(this.getVersionName().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        popView.findViewById(R.id.img_update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //显示视图
        popupWindow.setContentView(popView);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x3F000000));//全透明背景
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER,0,0);
    }



    public boolean delete(String delFile) {
        File file = new File(delFile);
        if (!file.exists()) {
            Log.e("delete", "Delete file Error:" + delFile + " not have！");
            return false;
        } else {
            if (file.isFile())
                return deleteSingleFile(delFile);
        }
        return false;
    }

    /** 删除单个文件
     * @param filePath$Name 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    private boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("--deleteSingleFile--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return true;
            } else {
                Log.e( "--deleteSingleFile--","删除单个文件" + filePath$Name + "失败！");
                return false;
            }
        } else {
            Log.e( "--deleteSingleFile--","删除单个文件失败：" + filePath$Name + "不存在！");
            return false;
        }
    }


    private void installAPK() {

        //setPermission(pathstr);
        Log.e(TAG,"installAPK1->pathstr:"+ apkpath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= 24) {
            //Toast.makeText(this,"准备安装新版本->"+pathstr,Toast.LENGTH_SHORT).show();
            Log.e(TAG,"installAPK2->pathstr:"+ apkpath);
            File file = (new File(apkpath));
            if (file.exists()){
                //Toast.makeText(this,"准备安装新版本->"+pathstr,Toast.LENGTH_SHORT).show();
                Log.e( "--installAPK--","准备安装新版本->"+ apkpath);
            } else {
                //Toast.makeText(this,"准备安装新版本->"+pathstr+"但文件不存在！",Toast.LENGTH_SHORT).show();
                Log.e( "--installAPK--","准备安装新版本->"+ apkpath +"但文件不存在！");
            }
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
            Log.e("installAPK", String.valueOf(apkUri));
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            Log.e("installAPK","SetOK");
            //兼容8.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity();
                    return;
                }
            }
        } else {
            intent.setDataAndType(Uri.fromFile(new File(apkpath)), "application/vnd.android.package-archive");
        }
        startActivity(intent);

    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    private void startInstallPermissionSettingActivity() {
        Uri packageUri = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 10086);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086) {
            installAPK();
        }
    }

}
